package top.frsf.pattern.c_behavioral.a_strategy.send;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/**
 * @author He Kuntao
 * @since 2024/8/16 11:22
 */
@Configuration
public class MsgSendStrategyContext implements ApplicationContextAware {

  @Resource
  private ApplicationContext applicationContext;

  public static final Map<String, String> strategyMap = new HashMap<>();

  /**
   * 扫描策略类
   */
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    applicationContext.getBeansWithAnnotation(MsgSendAno.class).forEach(
        (name, bean) -> {
          MsgSendAno msgSendAno = bean.getClass().getAnnotation(MsgSendAno.class);
          strategyMap.put(msgSendAno.name(), name);
        }
    );
  }

  /**
   * 根据策略名称获取策略类
   *
   * @param name 策略类型
   * @return 策略类
   */
  public IMsgSendStrategy getStrategyByName(String name) {
    String beanName = strategyMap.get(name);
    return beanName == null ? null : applicationContext.getBean(beanName, IMsgSendStrategy.class);
  }

}
